package com.pangda.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pangda.common.constant.BusinessStatusConstant;
import com.pangda.common.domain.PageResult;
import com.pangda.common.utils.UserContext;
import com.pangda.mapper.ActivityMapper;
import com.pangda.mapper.CoursesMapper;
import com.pangda.pojo.*;
import com.pangda.mapper.ContractMapper;
import com.pangda.pojo.dto.ContractDto;
import com.pangda.pojo.dto.DeptDataList;
import com.pangda.pojo.vo.ContractVo;
import com.pangda.service.IContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pangda.service.ISysUserService;
import org.apache.poi.hpsf.Decimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 合同表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-06-20
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements IContractService {

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CoursesMapper coursesMapper;

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ISysUserService userService;



    @Override
    public void insert(Contract contract) {
        Courses courses = coursesMapper.selectById(contract.getCourseId());
        Activity activity = activityMapper.selectById(contract.getActivityId());
        Integer price = courses.getPrice();
        BigDecimal discount = activity.getDiscount();
        contract.setOrderAmount(new BigDecimal(price).multiply(discount));
        contract.setCreateBy(UserContext.getUser());
        contract.setCreateTime(LocalDateTime.now());
        contractMapper.insert(contract);
    }

    /**
     * 客户分页查询
     *
     * @param pageResult  分页参数
     * @param contractDto 查询参数
     * @return
     */
    @Override
    public PageResult contractStatisticsList(PageResult pageResult, ContractDto contractDto) {
        Page<Contract> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());

        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtil.isNotEmpty(contractDto.getCreateBy()), Contract::getCreateBy, contractDto.getCreateBy())
                .between(ObjectUtil.isNotEmpty(contractDto.getEndCreateTime()) && ObjectUtil.isNotEmpty(contractDto.getBeginCreateTime()),
                        Contract::getCreateTime, contractDto.getBeginCreateTime(), contractDto.getEndCreateTime())
                .eq(ObjectUtil.isNotEmpty(contractDto.getChannel()), Contract::getChannel, contractDto.getChannel());
        page(page, wrapper);
        return PageResult.success(page, ContractVo.class);

    }

    @Override
    public PageResult deptStatisticsList(DeptDataList deptDataList) {
        String beginCreateTime = deptDataList.getBeginCreateTime();
        String endCreateTime = deptDataList.getEndCreateTime();
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; // ISO格式，例如 "2023-01-01"
        // 使用DateTimeFormatter来解析字符串为LocalDate
        LocalDate beginDate =  LocalDate.parse(beginCreateTime, formatter);
        LocalDate endDate =  LocalDate.parse(endCreateTime, formatter);
        List<DeptDataList> deptDataList1 =   contractMapper.selectAmountByDeptId(beginDate,endDate);
        PageResult<DeptDataList> success = PageResult.success(deptDataList1, DeptDataList.class);
        success.setTotal((long) deptDataList1.size());
        return success ;
    }

    @Override
    public Map<String, Object> salesStatistics(String beginCreateTime, String endCreateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; // ISO格式，例如 "2023-01-01"
        // 使用DateTimeFormatter来解析字符串为LocalDate
        LocalDate beginDate =  LocalDate.parse(beginCreateTime, formatter);
        LocalDate endDate =  LocalDate.parse(endCreateTime, formatter);
        List<Map<String,Object>> list = contractMapper.salesStatistics(beginDate,endDate);
        Map<String, Object> response = new HashMap<>();
        ArrayList<String> dates = new ArrayList<>();
        ArrayList<BigDecimal> nums = new ArrayList<>();
        ArrayList<Map<String,Object>> m = new ArrayList<>();
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("name","销售统计");
        stringObjectMap.put("data",nums);
        m.add(stringObjectMap);
        list.stream().forEach(map ->{
                String i = String.valueOf(map.get("time"));
                BigDecimal o = (BigDecimal) map.get("amount");
                dates.add(i);
                nums.add(o);

        });
        response.put("xAxis",dates);
        response.put("series",m);
        return response;
    }

    @Override
    public Map<String, Object> contractStatistics(String beginCreateTime, String endCreateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; // ISO格式，例如 "2023-01-01"
        // 使用DateTimeFormatter来解析字符串为LocalDate
        LocalDate beginDate =  LocalDate.parse(beginCreateTime, formatter);
        LocalDate endDate =  LocalDate.parse(endCreateTime, formatter);
        List<Map<String,Object>> list = contractMapper.contractStatistics(beginDate,endDate);
        Map<String, Object> response = new HashMap<>();
        ArrayList<String> dates = new ArrayList<>();
        ArrayList<Long> nums = new ArrayList<>();
        ArrayList<Map<String,Object>> m = new ArrayList<>();
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("name","新增客户数");
        stringObjectMap.put("data",nums);
        Map<String, Object> m2 = new HashMap<>();
        m2.put("name","客户总数");
        m.add(stringObjectMap);
        m.add(m2);
        list.stream().forEach(map ->{
            String i = String.valueOf(map.get("time"));
            Long o = (Long) map.get("num");
            dates.add(i);
            nums.add(o);
        });
        List<Map<String,Object>> list1 = contractMapper.CostumerTotal(beginDate,endDate);
        ArrayList<BigDecimal> nums1 = new ArrayList<>(nums.size());
        list1.stream().forEach(map ->{
            BigDecimal o = (BigDecimal) map.get("total");
            nums1.add(o);
        });
        m2.put("data",nums1);
        response.put("xAxis",dates);
        response.put("series",m);
        return response;
    }


}
